package com.eud.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.eud.service.impl.*;
import com.eud.entity.Movie;
import com.eud.service.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/AddMovieServlet")
@MultipartConfig
public class AddMovieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查是否为多部分内容
//    	String mName=request.getParameter("title");
//		
//		String mtype=request.getParameter("type");
//		String mdetail=request.getParameter("details");
//		String mactors=request.getParameter("actors");
//		String mdirector=request.getParameter("director");
//		String mrating=request.getParameter("rating");
//		String mboxOffice=request.getParameter("boxOffice");
    	
    	request.setCharacterEncoding("UTF-8");
    	MovieService m1 = new MovieServiceImpl();
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().println("Error: Form must have enctype=multipart/form-data.");
            return;
        }
        ServletContext context = request.getServletContext();
        String projectPath = context.getRealPath("/");
        String uploadPath = projectPath + "mImage";
        // 上传文件的目录
//        String uploadPath = "C:\\Users\\95\\Desktop\\image"; // 修改为实际的上传目录路径
        System.err.println(uploadPath);
        // 创建上传目录（如果不存在）
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            if (!uploadDir.mkdir()) {
                response.getWriter().println("Failed to create directory for uploads.");
                return;
            }
        }
        Map<String, String> formFields = new HashMap<>();
        Map<String, String> uploadedFiles = new HashMap<>();

        try {
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            String title = null;
            String description = null;

            for (FileItem item : items) {
                if (item.isFormField()) {
                    // 普通表单字段
                	  String fieldName = item.getFieldName();
                      String fieldValue = item.getString("UTF-8");
                      formFields.put(fieldName, fieldValue);
                } else {
                    // 文件字段
                    String fieldName = item.getFieldName();
                    String fileName = new File(item.getName()).getName();
                    if (fileName == null || fileName.trim().isEmpty()) {
                        continue; // Skip empty file inputs
                    }
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                   
                    // 写入文件
                    item.write(storeFile);

                    // 记录上传的文件名
                    uploadedFiles.put(fieldName, fileName);
                }
            }
            String url=uploadedFiles.get("poster");
            String url1=uploadedFiles.get("still");
            String mName = formFields.get("name");
            String mtype = formFields.get("type");
            String mdetail = formFields.get("details");
            String mactors = formFields.get("actors");
            String mdirector = formFields.get("director");
            String time = formFields.get("time");
            String ftime = formFields.get("ftime");
            double pf = 0;
            double piaof = 0;
            double pri = 0;
            String mrating = formFields.get("rating");
            if (mrating != null && !mrating.isEmpty()) {
                pf = Double.parseDouble(mrating);
            }
            String mboxOffice = formFields.get("boxOffice");
            if (mboxOffice != null && !mboxOffice.isEmpty()) {
                piaof = Double.parseDouble(mboxOffice);
            }
            String price = formFields.get("price");
            if (price != null && !price.isEmpty()) {
                pri = Double.parseDouble(price);
            }
    		System.err.println(mName+url+mtype);
    		Movie m=new Movie(mName,mactors,mdirector,mdetail,time,mtype,pf,pri,piaof,ftime,url,url1);
//    		!mName.equals("")
    		if((!mName.equals("")) && (!mactors.equals("")) && (!mdirector.equals("")) && (!mdetail.equals("")) &&(!time.equals("")) &&(!mtype.equals(""))&&(!ftime.equals(""))&& pri!=0 && pf!=0&& piaof!=0 ) {
    			m1.add(m);
    		}
    		
    		
            // 输出上传的文件名
//            for (Map.Entry<String, String> entry : uploadedFiles.entrySet()) {
//                System.out.println("Field Name: " + entry.getKey() + ", File Name: " + entry.getValue());
//            }
           
            // 确认上传成功
            response.getWriter().println("电影上传成功！");

        } catch (Exception ex) {
            ex.printStackTrace();
            response.getWriter().println("上传失败：" + ex.getMessage());
        }
    }
}